package com.studentsys.filter;

import com.studentsys.bean.Admin;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
@WebFilter("/*")
public class LoginFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response= (HttpServletResponse) resp;
        //验证用户是否已登录
        HttpSession session = request.getSession();
        Admin admin = (Admin) session.getAttribute("admin");
        //判断与登录相关页面或servlet需要直接放行
        String requestURI = request.getRequestURI();
        if (requestURI.contains("login")||requestURI.contains("admin")||requestURI.contains("regist")){
            //放行
            filterChain.doFilter(request,response);
        }else{
            if (admin == null){
                //跳转到登录页面
                response.sendRedirect("login.jsp");
            }else{
                filterChain.doFilter(request,response);
            }
        }
    }

    @Override
    public void destroy() {

    }
}
